import router from "@/router";

import currencyRoutes from "../../router/modules/currencyRoutes";
import asyncRoutesLib from "../../router/modules/asyncRoutes";

const permission = {
  namespaced: true,
  state: {
    routes: null,
    addRoutes: null
  },
  mutations: {
    setRoutes (state, addRoutes) {
      state.routes = [...currencyRoutes, ...addRoutes];
      state.addRoutes = addRoutes;
    }
  },
  actions: {
    getAsyncRoutes ({ commit, rootGetters }, permissionArr) {
      // 提取asyncRoutes动态路由
      function extractRoute (route, permissionArr) {
        let arrNew = [];
        for (let item of route) {
          let itemNew = { ...item }; //解决浅拷贝共享同一内存地址
          if (permissionArr.includes(itemNew.name)) {
            if (itemNew.children) {
              itemNew.children = extractRoute(itemNew.children, permissionArr);
            }
            arrNew.push(itemNew);
          }
        }
        return arrNew;
      }
      let addRoutes = [];
      if (rootGetters.userName === "admin") {
        addRoutes = asyncRoutesLib || "";
      } else {
        addRoutes = extractRoute(asyncRoutesLib, permissionArr);
      }
      addRoutes.push({ path: "*", redirect: "/404", hidden: true });
      commit("setRoutes", addRoutes);
      router.addRoutes(addRoutes);
      return addRoutes;
    }
  }
};
export default permission;
